//
//  RegistWorkerController.swift
//  mggz
//
//  Created by Apple on 2018/5/18.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

class RegistWorkerController: UITableViewController {

    @IBOutlet weak var headImgview: UIImageView!
    @IBOutlet weak var workNumview: UILabel!
    @IBOutlet weak var workerType: UILabel!
    @IBOutlet weak var kqview: UILabel!
    @IBOutlet weak var gzField: UITextField!
    @IBOutlet weak var telField: UITextField!
    @IBOutlet weak var jgType: UILabel!
    
    @IBOutlet weak var complete: UIButton!
    
    var currentProject:LCProjectListModel?
    var information:NSMutableArray?
    var birthday:String?
    var headimg,sfzimg:UIImage?
    var emptyData = [String:Any]()
    var gzArray = [(String,String,String)]()
    
    var age:Int?
    var calculateWay:Double?
    
    var workerNumType:Bool?
    
    var imgResult:[ImageUploadModel]?
    var companyID:String?
    var selectGz = -1
    var selectKq = -1
    
    var guid:String?
    
    var timeNameArray = [(String,String,String)]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 40;
        self.complete.layer.cornerRadius = 5
        self.complete.layer.masksToBounds = true
        self.gzField.delegate = self
        self.getGzList()
        self.MakeWorkerNum()
        self.getJGType()
        self.headImgview.image = self.headimg
        self.gzField.keyboardType = .numberPad
        self.telField.keyboardType = .numberPad
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.headImgview.angle = self.headImgview.bounds.width/2
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /**
     *验证工号
     */
    func MakeWorkerNum(){
        let currentDay = Calendar.current.dateComponents([.year,.month,.day], from: Date())
        let year = String(currentDay.year ?? 0)
        var month = (currentDay.month!)<10 ? "0\((currentDay.month!))" : "\(currentDay.month!)"
        var day = currentDay.day! < 10 ? "0\(String(currentDay.day!))" : String(currentDay.day!)
        var lastNum = self.birthday?.getSubstring(14, end: 18)
        var result = year.getSubstring(2, end: 4) + (month ?? "") + day + (lastNum ?? "")
        print("\(result)")
        
        var openYear = self.birthday?.getSubstring(6, end: 10)
        self.age = (Int(year) ?? 0) - (Int(openYear!) ?? 0)
        
        var params:[String:Any] = ["migrantWorkerNo":result]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .GHYZ, params: &params, type: WorkerNum.self, success: { (bean,_) in
            guard let data = bean as? WorkerNum else {
                return
            }
            self.workNumview.text = data.Result
        }) { (error) in
            
        }
        
    }
    
    //获取guid
    func setupGetUdid(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiMainManager.request(.GETLCNewGuid(number: 1, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["Status"]) as! String == "OK" else{
                    return
                }
                self.guid = (jsonString["Guid"] as! String)
            }
        }
        
    }
    
    //获取工种
    func getGzList(){
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .GZLIST, params: &emptyData, type: GZTypeList.self, success: { (bean,_) in
            guard let data = bean as? GZTypeList else{
                return
            }
            data.Result?.forEach({ (item) in
                self.gzArray.append((item.WorkType ?? "","",item.ID ?? ""))
            })
            self.getTimeList()
        }) { (error) in
            
        }
    }
    //获取时间列表
    func getTimeList(){
        var params:[String:Any] = ["start":"0","limit":"100","orderManagerConfigId":"862BCA72-AB8A-B2ED-520B-A14C2BE74850"]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQSJLIST, params: &params, type: KQSJList.self, success: { (bean,_) in
            guard let data = bean as? KQSJList else{
                return
            }
            
            data.Result?.Items?.forEach({ (item) in
                var str = ""
                if (item.BeginTime ?? "").count > 16{
                    str += (item.BeginTime ?? "").getSubstring(11, end: 16)
                }
                str += "-"
                if item.IsLastDay ?? false {
                    str += "第二天"
                }
                if (item.EndTime ?? "").count > 16{
                    str += (item.EndTime ?? "").getSubstring(11, end: 16)
                }
                self.timeNameArray.append((item.WorkTimeQuantumName ?? "",str,item.ID ?? ""))
            })
        }) { (error) in
            
        }
    }
    
    //获取计工方式
    func getJGType(){
        var params:[String:Any] = ["contructionCompanyID":self.currentProject?.CompanyID ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .JGFS, params: &params, type: Jgfs.self, success: { (bean,_) in
            guard let data = bean as? Jgfs else{
                return
            }
            self.workerNumType = data.Result == 2 ? false:true
            self.calculateWay = data.Result ?? 0
            self.gzField.text = data.Result == 2 ? "20":"200"
            self.jgType.text = data.Result == 2 ? "元/小时":"元/工"
        }) { (error) in
            
        }
    }
    
    //上传图片
    func upImglist(){
        
            var pattern = "^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\\d{8}$"
            let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
            let flag = predicate.evaluate(with: self.telField.text ?? "")
            
            if self.selectGz == -1 {
                QWTextonlyHud("请先选择工种", target: self.view)
                return
            }else if self.selectKq == -1{
                QWTextonlyHud("请先选择考勤时段", target: self.view)
                return
            }else if !flag{
                QWTextonlyHud("请填写正确的手机号", target: self.view)
                return
            }else if self.workerNumType ?? false && (self.gzField.text == nil || self.gzField.text! == "" || ((self.gzField.text as NSString?)?.doubleValue)! < Double(50)) {
                QWTextonlyHud("日薪不能少于50元/工", target: self.view)
                return
            }
            QWTextWithStatusHud("正在上传...", target: self.view)
            ImageUploadModel.commitImage([self.headimg!,self.sfzimg!]) { (response) in
                
                if response.success {
                    if let arr = response.value, arr.count > 0 {
                        self.imgResult = arr
                        self.upWorkerMsg()
                    }else {
                        QWHudDiss(self.view)
                        //WWError("上传图片出错")
                        QWTextonlyHud("上传图片出错", target: self.view)
                    }
                }
                else {
                    QWHudDiss(self.view)
                    QWTextonlyHud("网络异常", target: self.view)
                }
            }
        
    }
    
    //上传基本信息 //{"State":"OK","Result":"165630a1-266b-4899-90c2-a7b698336919","Msg":"民工快速注册成功！","Err":""}
    func upWorkerMsg(){
        
        
        
        //QWTextWithStatusHud("正在提交...", target: self.view)
        var params:[String:Any] = ["lealPersonIDCard":self.birthday ?? "","cellPhoneNumber":self.telField.text ?? "","name":self.information?.object(at: 0) as? String ?? "","sex":self.information?.object(at: 3) as? String ?? "","age":self.age ?? "","address":self.information?.object(at: 4) as? String ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .QueckRegister, params: &params, type: BaseRegister.self, success: { (bean,_) in
            guard let data = bean as? BaseRegister else{
                QWHudDiss(self.view)
                return
            }
            self.companyID = data.Result ?? ""
            self.upConserve()
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .DATAERROR:
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .DATAFAIL:
                QWTextonlyHud("数据异常", target: self.view)
                break
            case .HTTPERROR:
                QWTextonlyHud("网络异常", target: self.view)
                break
            case .StateFail(let data):
                guard let dic = data as? Dictionary<String,Any> else{
                    guard let str = data as? String else{
                        return
                    }
                    QWTextonlyHud("\(str)", target: self.view)
                    return
                }
                QWTextonlyHud("\(dic["Msg"] as? String ?? "")", target: self.view)
                break
            }
        }
    }
    
    //上传民工工资条件
    func upConserve(){
        //var dc = Int(Double.init(arc4random()))
        var orderId = UUID
        
        var dic:[String:Any] = ["ID":orderId,"Form":["MigrantWorkerNo":self.workNumview.text ?? "","CompanyMG":["ID":self.companyID],"WorkStop":"0","IsBlacklist":"false",(self.calculateWay == 2 ?"HourSalary":"DaySalary"):self.gzField.text ?? "","WorkTimeQuantum":["ID":self.timeNameArray[(self.selectKq ?? 0)].2],"MigrantWorkType":["ID":self.gzArray[(self.selectGz ?? 0)].2]]]
        do{
            let data = try JSONSerialization.data(withJSONObject: dic, options: [])
            
            let resultstr=(String.init(data: data, encoding: .utf8))!
            print(resultstr)
            var params:[String:Any] = ["pageName":"MarTian.Edit.ShiGongDuiMinGongWeiHu","orderConfigId":"9820de03-9501-0e0e-04cf-210d98dba05e","orderId":orderId ?? "","operate":"1","jsonData":resultstr]
            
            
            MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .KQTIMESET, params: &params, type: SaveWorker.self, success: { (bean,_) in
                QWHudDiss(self.view)
                guard let data = bean as? SaveWorker else{
                    return
                }
                if data.State == "OK"{
                    QWTextonlyHud("保存成功!", target: self.view)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1.5, execute: {
                        
                        guard let vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count ?? 0)-2] as? EntryFirstpageViewController else{
                            return
                        }
                        vc.reset()
                        
                        self.navigationController?.popViewController(animated: true)
                    })
                }else{
                    QWTextonlyHud("提交失败，请重试", target: self.view)
                    //WWError("提交失败，请重试")
                }
                
            }) { (error) in
                QWHudDiss(self.view)
                switch error{
                case .DATAERROR:
                    QWTextonlyHud("数据异常", target: self.view)
                    break
                case .DATAFAIL:
                    QWTextonlyHud("数据异常", target: self.view)
                    break
                case .HTTPERROR:
                    QWTextonlyHud("网络异常", target: self.view)
                    break
                case .StateFail(let data):
                    guard let dic = data as? Dictionary<String,Any> else{
                        guard let str = data as? String else{
                            return
                        }
                        QWTextonlyHud("\(str)", target: self.view)
                        return
                    }
                    QWTextonlyHud("\(dic["Msg"] as? String ?? "")", target: self.view)
                    break
                }
            }
        }catch{
            print("error")
            QWHudDiss(self.view)
            WWError("提交失败，请重试")
        }
        
    }
    
    
    @IBAction func viewClick(_ sender: UIButton) {
        switch sender.tag {
        case 0:
            var vc = SelectListDialog(nibName: "SelectListDialog", bundle: nil)
            vc.modalPresentationStyle = .overCurrentContext
            vc.selectBack = {
                index in
                self.workerType.text = self.gzArray[index].0
                self.selectGz = index ?? 0
            }
            self.present(vc, animated: false, completion: nil)
            vc.setData(self.gzArray)
            break
        case 1:
            var vc = SelectListDialog(nibName: "SelectListDialog", bundle: nil)
            vc.modalPresentationStyle = .overCurrentContext
            vc.selectBack = {
                index in
                self.kqview.text = self.timeNameArray[index].1
                self.selectKq = index ?? 0
            }
            self.present(vc, animated: false, completion: nil)
            vc.setData(self.timeNameArray)
            break
        case 2:
            self.upImglist()
            break
        default:
            break
        }
        
    }
    

    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
 

}

extension RegistWorkerController:UITextFieldDelegate{
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
}
